import { useRequest } from 'ahooks';
import { App, Form, Input, Modal, Spin, Select, Row, Col, message, Button } from 'antd';
import React, { useMemo, useEffect, useState, useCallback } from 'react';
import styles from './styles.module.css';
import { DthesaurusContent } from './dthesaurus-content';
import { useContext } from 'react';
import { useTranslation } from 'react-i18next';
import { termCreate, termUpdate, intelligentGenerationApi } from '@/client/api/domainThesaurus';
import { apiInterceptors } from '@/client/api';

interface CreatedomainModelProps {
  open: boolean;
  onCancel: () => void;
  refresh?: () => void;
  type?: 'add' | 'edit';
  tabType?: 'ProperNouns' | 'Synonym' | 'CaseLibrary';
}

const CreatetermModel: React.FC<CreatedomainModelProps> = ({
  open,
  onCancel,
  type = 'add',
  refresh,
  tabType = 'ProperNouns',
}) => {
  const { t } = useTranslation();
  const { termRow, sub, domainRow, options,login_name } = useContext(DthesaurusContent);
  const [form] = Form.useForm();
  const [standardName, setStandardName] = useState('');
  const [synonymList, setSynonymList] = useState<string[]>([]);
  const [formValues, setFormValues] = useState<any>({});
  const [latestInput, setLatestInput] = useState<string | null>(null);
  const [isLatestDuplicate, setIsLatestDuplicate] = useState(false);
  const [timer, setTimer] = useState<NodeJS.Timeout | null>(null);

  // 表单配置项
  const formItems = useMemo(() => {
    return tabType === 'ProperNouns'
      ? [
        {
          name: 'name',
          label: '专有名词',
          txt: '请输入专有名词',
          rules: [{ required: true, message: '专有名词不能为空' }],
        },
        {
          name: 'desc',
          label: '描述',
          rules: [{ required: true, message: '描述不能为空' }],
        },
      ]
      : tabType === 'Synonym'
        ? [
          {
            name: 'name',
            label: '标准词',
            txt: '请输入标准词',
            rules: [
              { required: true, message: '标准词不能为空' },
            ],
          },
          {
            name: 'desc',
            label: '同义词',
            rules: [{ required: true, message: '同义词不能为空' }],
          },
        ]
        : [
          {
            name: 'app_code',
            label: '所属应用',
            txt: '请选择应用编码',
            rules: [{ required: true, message: '所属应用不能为空' }],
          },
          {
            name: 'name',
            label: '用户输入',
            txt: '用户输入',
            rules: [{ required: true, message: '用户输入不能为空' }],
          },
          {
            name: 'desc',
            label: '期望输出',
            txt: '期望输出',
            rules: [{ required: true, message: '期望输出不能为空' }],
          },
        ];
  }, [t, tabType]);

  // 请求逻辑
  const { run: createDomain, loading: isSubmittingForm } = useRequest(
    async (params: any) => {
      if (type === 'edit') {
        return await termUpdate({
          ...params,
          creator: sub?sub:login_name,
          id: termRow.id,
          lexicon_domain_id: domainRow.id,
          type: tabType,
          desc: tabType === 'Synonym' ? params.desc.join(',') : params.desc
        });
      } else {
        return await termCreate({
          ...params,
          lexicon_domain_id: domainRow.id,
          type: tabType,
          desc: tabType === 'Synonym' ? params.desc.join(',') : params.desc
        });
      }
    },
    {
      manual: true,
      onSuccess: async (res) => {
        const {success,err_msg} = res.data||{}
        if(success){
           if (type === 'edit') {
          message.success('更新成功');
          } else {
            message.success('创建成功');
          }
          await refresh?.();
          onCancel();
        }else{
          message.error(err_msg||'操作失败');
        }
        
      }
    }
  );

  // 处理标准词输入
  const handleStandardNameChange = (value: string) => {
    setStandardName(value);
    form.setFieldsValue({ name: value });
  };

  // 处理同义词列表变更
  const handleSynonymChange = (values: string[]) => {
    const filteredValues = values.filter(Boolean);
    const uniqueValues: string[] = [];
    const seen: Set<string> = new Set();
    filteredValues.forEach((value, index) => {
      if (value === standardName) {
        message.warning(`"${value}" 不能与标准词相同`);
        return;
      }
      if (value.length > 80) {
        value = value.slice(0, 80);
        message.warning('每个同义词最多80字');
      }
      if (!seen.has(value)) {
        seen.add(value);
        uniqueValues.push(value);
      } else {
        message.warning(`"${value}" 已存在`);
      }
    });

    setSynonymList(uniqueValues);
    form.setFieldsValue({ desc: uniqueValues });
  };

  // 搜索同义词
  const handleSearch = (value: string) => {
    setLatestInput(value);
    if (synonymList.includes(value)) {
      message.warning('该同义词已存在');
      setIsLatestDuplicate(true);
    } else {
      setIsLatestDuplicate(false);
    }
  };

  // 回车事件处理
  const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      if (isLatestDuplicate && latestInput !== null) {
        const lastIndex = synonymList.lastIndexOf(latestInput);
        if (lastIndex !== -1) {
          setTimeout(() => {
            message.warning(`已移除重复的同义词 "${latestInput}"`);
            setSynonymList(synonymList);
            form.setFieldsValue({ desc: synonymList });
          }, 100)
        }
        setIsLatestDuplicate(false);
        setLatestInput(null);
      }
    }
  };

  // 智能生成
  const intelligentGeneration = useCallback(() => {
    if (tabType !== 'CaseLibrary') {
      const nameValue = form.getFieldValue('name')?.trim();
      if (!nameValue) {
        message.warning(`请先录入${tabType === 'ProperNouns' ? '专有名词' : '标准词'}`);
        return;
      }
      getintelligentGeneration(domainRow.id, nameValue);
    }
  }, [tabType, message, form, domainRow.id]);

  // 智能生成请求
  const { run: getintelligentGeneration, loading: isGenerating } = useRequest(
    async (lexicon_domain_id, name) => {
      return await intelligentGenerationApi({ lexicon_domain_id, name });
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success } = res.data;
        if (success) {
          const descValue = form.getFieldValue('desc') || [];
          const generatedSynonyms = data.synonym;
          const descValueConcat = [...new Set([...descValue, ...generatedSynonyms])];
          const testkown = data.content;
          if (tabType === 'Synonym') {
            setSynonymList(descValueConcat);
            form.setFieldsValue({ desc: descValueConcat });
          } else {
            if (timer) {
              clearInterval(timer);
            }
            let displayText = '';
            let index = 0;
            const newTimer = setInterval(() => {
              if (index < testkown.length) {
                displayText += testkown[index];
                index++;
                form.setFieldsValue({ desc: displayText });
              } else {
                clearInterval(newTimer);
                setTimer(null);
              }
            }, 100);
            setTimer(newTimer);
          }
        }
      }
    }
  );

  // 监听表单值变化
  const handleValuesChange = useCallback((changedValues: any, allValues: any) => {
    setFormValues(allValues);
    if (changedValues.name !== undefined) {
      setStandardName(changedValues.name);
    }
  }, []);

  // 组件挂载时初始化表单值
  useEffect(() => {
    if (termRow) {
      const initialData = {
        name: termRow.name || '',
        desc: tabType === 'Synonym'
          ? (termRow.desc ? termRow.desc : [])
          : termRow.desc || '',
        app_code: termRow.app_code || ''
      };

      form.setFieldsValue(initialData);
      setFormValues(initialData);
      setStandardName(initialData.name || '');
    }
  }, [termRow, tabType, form]);
  useEffect(() => {
    return () => {
      if (timer) {
        clearInterval(timer);
      }
    };
  }, [timer]);

  // 组件渲染
  return (
    <Modal
      className={styles['modal-container']}
      title={
        type === 'edit'
          ? tabType === 'ProperNouns'
            ? '编辑专有名词'
            : tabType === 'Synonym'
              ? '编辑同义词'
              : '编辑案例库'
          : tabType === 'ProperNouns'
            ? '创建专有名词'
            : tabType === 'Synonym'
              ? '创建同义词'
              : '创建案例库'
      }
      width={800}
      open={open}
      okButtonProps={{ disabled: isSubmittingForm || isGenerating }}
      onCancel={onCancel}
      centered
      footer={
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          {tabType !== 'CaseLibrary' ? (
            <Button
              onClick={intelligentGeneration}
              type="primary"
              style={{ width: '8rem' }}
              loading={isGenerating}
            >
              {isGenerating ? '生成中' : '智能生成'}
            </Button>
          ) : (
            <div></div>
          )}
          <div>
            <Button onClick={onCancel} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button
              type="primary"
              onClick={async () => {
                try {
                  const values = await form.validateFields();
                  await createDomain(values);
                } catch (error) {
                  console.error('提交失败:', error);
                }
              }}
              loading={isSubmittingForm}
            >
              {isSubmittingForm ? '提交中' : '确定'}
            </Button>
          </div>
        </div>
      }
    >
      <Spin spinning={isSubmittingForm || isGenerating}>
        {tabType === 'CaseLibrary' ? (
          <Form
            form={form}
            initialValues={termRow}
            labelAlign="left"
            layout={'vertical'}
            onValuesChange={handleValuesChange}
          >
            {formItems.map((item, index) => {
              const { name, label, rules, txt } = item;
              if (name === 'app_code') {
                return (
                  <Form.Item
                    key={name}
                    {...{ name, label, rules }}
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 24 }}
                  >
                    <Select
                      defaultValue=""
                      allowClear
                      options={options}
                      placeholder="所属应用"
                    />
                  </Form.Item>
                );
              }
              if (name === 'name') {
                return (
                  <Row key="case-row" style={{ marginBottom: 16 }}>
                    <Col span={11}>
                      <Form.Item
                        {...{ name, label, rules }}
                        labelCol={{ span: 7 }}
                        wrapperCol={{ span: 24 }}
                      >
                        <Input.TextArea
                          maxLength={500}
                          placeholder={txt}
                          rows={5}
                          autoComplete="off"
                          showCount
                        />
                      </Form.Item>
                    </Col>
                    <Col span={11} offset={2}>
                      <Form.Item
                        {...{ name: 'desc', label: '期望输出', rules: formItems.find(i => i.name === 'desc')?.rules }}
                        labelCol={{ span: 7 }}
                        wrapperCol={{ span: 24 }}
                      >
                        <Input.TextArea
                          maxLength={500}
                          placeholder={formItems.find(i => i.name === 'desc')?.txt}
                          rows={5}
                          autoComplete="off"
                          showCount
                        />
                      </Form.Item>
                    </Col>
                  </Row>
                );
              }
              return null;
            })}
          </Form>
        ) : (
          <Form
            form={form}
            labelAlign="left"
            initialValues={termRow}
            onValuesChange={handleValuesChange}
          >
            {formItems.map((item, index) => {
              const { name, label, rules, txt } = item;
              return (
                <Form.Item
                  key={name}
                  {...{ name, label, rules }}
                  labelCol={{ span: 3 }}
                  wrapperCol={{ span: 21 }}
                >
                  {name === 'app_code' ? (
                    <Select
                      defaultValue=""
                      allowClear
                      options={options}
                      placeholder="所属应用"
                    />
                  ) : name === 'name' ? (
                    <Input
                      maxLength={80}
                      placeholder={txt}
                      autoComplete="off"
                      showCount
                      onChange={(e) => handleStandardNameChange(e.target.value)}
                    />
                  ) : name === 'desc' && tabType === 'Synonym' ? (
                    <Select
                      mode="tags"
                      style={{ width: '100%' }}
                      placeholder="请输入同义词（按回车确认）"
                      onChange={handleSynonymChange}
                      filterOption={() => true}
                      onSearch={handleSearch}
                      onInputKeyDown={handleInputKeyDown}
                      maxTagTextLength={10}
                      maxTagCount={3}
                      maxCount={20}
                    />
                  ) : (
                    <Input.TextArea
                      maxLength={tabType === 'ProperNouns' ? 200 : 500}
                      placeholder={txt}
                      rows={5}
                      autoComplete="off"
                      showCount
                    />
                  )}
                </Form.Item>
              );
            })}
          </Form>
        )}
      </Spin>
    </Modal>
  );
};

export default CreatetermModel;    